const Path = require("path");
const { File } = require("ada-util");
const { md5 } = require("ada-util/src/md5");

module.exports = function ({ content, path, option, fileInfo }) {
    const sass = require(Path.resolve(option.nmodulePath, './sass'));
    let t = content.match(/@import (['|"])[\s\S]+?\1;/g) || [];
    t = t.map(a => {
        let m = a.substring(9, a.length - 2).trim();
        if (m[0] === '.' || m[0] === '/') {
            return m;
        } else {
            return `node_modules/${m}`;
        }
    });
    return new Promise((resolve, reject) => {
        if (option.develop) {
            sass.render(Object.assign({
                file: path,
                sourceMap: "string",
                sourceMapContents: true
            }, option.compiler.sass), function (err, result) {
                if (!err) {
                    let map = JSON.parse(result.map.toString());
                    let filename = fileInfo.required;
                    map.file = option.siteURL + filename;
                    map.sources = map.sources.map(_path => {
                        _path = Path.resolve(option.projectPath, `./${_path}`).replace(/\\/g, "/");
                        return option.siteURL + (_path.indexOf("node_modules") === -1 ? _path.substring(option.sourcePath.length) : "node_modules/" + _path.substring(option.nmodulePath.length));
                    });
                    let _result = result.css.toString() || `#${md5("empty")}{font-size:10px}`;
                    _result = _result.replace(/\/\*# sourceMappingURL[\s\S]+?\*\//g, "");
                    _result = _result + `\n/*# sourceMappingURL=${option.siteURL}${map.file}.map*/\n`;
                    let _f = '';
                    t.forEach(b => _f += `url("${b}");\n`);
                    _result = _result + `/* ${_f} */`;
                    new File(Path.resolve(option.distPath, `./${filename}.map`)).write(JSON.stringify(map)).then(() => {
                        resolve(_result);
                    });
                } else {
                    reject(err);
                }
            });
        } else {
            sass.render(Object.assign({
                file: path
            }, option.compiler.sass), function (err, result) {
                if (!err) {
                    resolve(result.css.toString() || `#${md5("empty")}{font-size:10px}`);
                } else {
                    reject(err);
                }
            });
        }
    });
};